#include<iostream>
#include<vector>
#include<queue>
#include<string>
using namespace std;



struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left),
        right(right) {}
};
 
class Solution {
public:
    bool is_intree(TreeNode* root, TreeNode* x) {
        if (root == nullptr) {
            return false;
        }

        return root == x || is_intree(root->left, x) ||
            is_intree(root->right, x);
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

        if (root == nullptr) {
            return nullptr;
        }

        if (root == q || root == p) {
            return root;
        }
        bool qleft = is_intree(root->left, q);
        bool qright = !qleft;
        bool pleft = is_intree(root->left, p);
        bool pright = !pleft;

        if (qleft && pright || qright && pleft) {
            return root;
        }
        else if (qleft && pleft) {
            return lowestCommonAncestor(root->left, p, q);
        }
        else {
            return lowestCommonAncestor(root->right, p, q);
        }
    }
};